"use client";

import { useState } from "react";
// import { Button } from "@heroui/button";
// import { Image } from "@heroui/image";
// import { Input, Textarea } from "@heroui/input";
// import { Spinner } from "@heroui/spinner";
// import { Skeleton } from "@heroui/skeleton";
import {
  Form,
  Input,
  Textarea,
  Image,
  Spinner,
  Skeleton,
  Button,
  addToast,
} from "@heroui/react";
// @ts-ignore
import Stepper from "react-stepper-horizontal";
import {
  EditIcon,
  CheckIcon,
  ArrowLeftIcon,
  CopyIcon,
} from "@nextui-org/shared-icons";

export default function PPTPage() {
  const [loading, setLoading] = useState<boolean>(false);
  const [title, setTitle] = useState<string>(""); //主题
  const [request, setRequest] = useState<string>(
    "阅读分析文章内容, 分别列出基础，进阶，挑战，三级知识点，每个知识点不少于3项",
  ); //要求
  const [content, setContent] = useState<string>("");
  const [pptInfo, setPPTInfo] = useState<any>();
  const [template, setTemplate] = useState<any>({});
  const [templateId, setTemplateId] = useState<string>("");
  const [step, setStep] = useState<number>(0);

  const handleCreateContent = async () => {
    if (!title) {
    } else if (!request) {
    } else {
      setLoading(true);
      setStep(1);

      const content = `${title}, ${request}`;
      const response = await fetch("/api/ppt/outline", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ content }),
      });

      if (!response.ok) throw new Error("请求失败");
      const json = await response.json();

      setContent(json.toString());
      setLoading(false);
    }
  };

  const handleSelectTemplate = async () => {
    setLoading(true);
    setStep(2);

    if (!template.records) {
      const response = await fetch("/api/ppt/template", {
        method: "GET",
        headers: { "Content-Type": "application/json" },
      });

      if (!response.ok) throw new Error("请求失败");
      const data = await response.json();

      setTemplate(data);
    }
    setLoading(false);
  };

  const handleCreateFile = async () => {
    if (templateId) {
      setLoading(true);
      setStep(3);

      const response = await fetch("/api/ppt/file", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ content, templateId }),
      });

      if (!response.ok) throw new Error("请求失败");
      const json = await response.json();

      setPPTInfo(json);
      setLoading(false);
    } else {
      debugger;
      addToast({
        title: "请选择一个模版",
        description: "ddd",
        color: "danger",
      });
    }
  };

  const handleDownload = async () => {
    window.open(pptInfo?.pptUrl, "_blank");
  };

  const handleBack = () => {
    const lastStep = step - 1;

    setStep(lastStep);
  };

  const getSkeleton = (count: number) => {
    const elements = [];

    for (let i = 0; i < count; i++) {
      elements.push(
        <Skeleton key={i} className="w-4/5 rounded-lg">
          <div className="h-3 w-4/5 rounded-lg bg-default-200" />
        </Skeleton>,
      );
    }

    return elements;
  };

  const getSkeleton2 = (count: number) => {
    const elements = [];

    for (let i = 0; i < count; i++) {
      elements.push(
        <Skeleton key={i} className="rounded-lg">
          <div className="h-24 rounded-lg bg-default-300" />
        </Skeleton>,
      );
    }

    return elements;
  };

  return (
    <div>
      <div>
        <Stepper
          activeStep={step}
          steps={[
            { title: "输入主题" },
            { title: "生成大纲" },
            { title: "选择模版" },
            { title: "生成文件" },
          ]}
        />
      </div>
      <div className="mt-10 px-32">
        {step == 0 && (
          <div>
            <Form className="w-full" onSubmit={handleCreateContent}>
              <div className="mb-2">主题：</div>
              <Input
                isRequired
                className="mb-5"
                errorMessage="请填写主题"
                placeholder="输入文章的主题，例如：滕王阁序"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
              />
              <div className="mb-2">要求：</div>
              <Textarea
                isRequired
                errorMessage="请填写要求"
                minRows={5}
                placeholder="阅读分析文章内容, 分别列出基础，进阶，挑战，三级知识点，每个知识点不少于3项"
                value={request}
                onChange={(e) => setRequest(e.target.value)}
              />
              <div className="text-center mt-10 w-full">
                <Button
                  color="primary"
                  disabled={loading}
                  size="lg"
                  startContent={<EditIcon />}
                  type="submit"
                >
                  生产PPT大纲
                </Button>
              </div>
            </Form>
          </div>
        )}
        {step == 1 && (
          <div>
            <div>
              <div className="mb-2">PPT大纲</div>
              {loading && (
                <div className="space-y-5 p-4 bg-gray-100 rounded-lg">
                  {getSkeleton(5)}
                </div>
              )}
              {!loading && <Textarea maxRows={20} value={content} />}
            </div>
            <div className="flex justify-center gap-5 mt-10">
              <Button
                color="primary"
                size="lg"
                startContent={<ArrowLeftIcon />}
                variant="bordered"
                onPress={handleBack}
              >
                返回上一步
              </Button>
              <Button
                color="primary"
                disabled={loading}
                size="lg"
                startContent={<CopyIcon />}
                onPress={handleSelectTemplate}
              >
                选择PPT模版
              </Button>
            </div>
          </div>
        )}
        {step == 2 && (
          <div>
            <div className="p-2">选择一个PPT模版</div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-2">
              {loading && getSkeleton2(5)}
              {!loading &&
                template.records?.map((t: any) => (
                  <div key={t.templateIndexId} className="p-2 relative">
                    <Image
                      className={`transition hover:scale-110 ${t.templateIndexId == templateId ? "brightness-50 scale-110" : ""}`}
                      src={JSON.parse(t.detailImage).titleCoverImage}
                      width={250}
                      onClick={() => setTemplateId(t.templateIndexId)}
                    />
                    {t.templateIndexId == templateId && (
                      <div className="bg-white size-7 rounded-full z-50 absolute top-4 left-4 p-1">
                        <CheckIcon className="text-xl" />
                      </div>
                    )}
                  </div>
                ))}
            </div>
            <div className="flex justify-center gap-5 mt-10">
              <Button
                color="primary"
                size="lg"
                startContent={<ArrowLeftIcon />}
                variant="bordered"
                onPress={handleBack}
              >
                返回上一步
              </Button>
              <Button
                color="primary"
                disabled={loading}
                size="lg"
                startContent={<CheckIcon />}
                onPress={handleCreateFile}
              >
                生产PPT
              </Button>
            </div>
          </div>
        )}
        {step == 3 && (
          <div>
            {!loading && (
              <div>
                <div className="flex justify-center">
                  <Image
                    className={`transition hover:scale-110`}
                    src={pptInfo?.coverImgSrc}
                    width={550}
                  />
                </div>
                <div className="mt-5 flex justify-center">
                  <Button
                    color="success"
                    size="lg"
                    startContent={<CheckIcon />}
                    onPress={handleDownload}
                  >
                    已生成, 点击下载
                  </Button>
                </div>
              </div>
            )}
            {loading && (
              <div className="flex flex-col content-center justify-center text-center">
                <Skeleton className="rounded-lg w-2/5 m-auto">
                  <div className="h-72 rounded-lg bg-default-300" />
                </Skeleton>
                <Spinner
                  className="mt-5"
                  color="primary"
                  label="PPT正在制作..."
                  labelColor="primary"
                />
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
